
#include "audio_capturer.h"

// #include "hal_display.h"
#include "codec_interface.h"

#include <algorithm>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

using namespace OHOS;
using namespace OHOS::Audio;
using namespace OHOS::Media;

void help(char **argv)
{
    ;
}

int main(int argc, char **argv)
{
    int ret;

    // ret = HalPlayerSysInit();
    // printf("----->> HalPlayerSysInit(%d) \n", ret);

    ret = CodecInit();
    printf("----->> CodecInit(%d) \n", ret);

    int fd = 0;
    if (argc > 1)
    {
        fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC);
        printf("----->> open(%d): %s\n", fd, argv[1]);
    }
    else
    {
        fd = open("/sdcard/tmp.aac", O_RDWR | O_CREAT | O_TRUNC);
        printf("----->> open(%d): /sdcard/tmp.aac \n", fd);
    }

    AudioCapturer *ac = new AudioCapturer();

    AudioCapturerInfo info;
    info.inputSource = AUDIO_MIC;
    info.audioFormat = AAC_LC;
    info.sampleRate = 16000;
    info.channelCount = 1;
    info.bitRate = 32000;
    info.streamType = TYPE_MEDIA;
    info.bitWidth = BIT_WIDTH_16;

    ret = ac->SetCapturerInfo(info);
    printf("----->> SetCapturerInfo(%d)\n", ret);

    printf("----->> Start(%d)\n", ac->Start() ? 0 : (-1));
    
    int frameSize = ac->GetFrameCount() * 2;
    printf("----->> GetFrameCount(%d)\n", frameSize);
    if (frameSize < 1)
    {
        if (fd > 0)
            close(fd);
        delete ac;
        return -1;
    }

    uint8_t buff[frameSize];
    int timeout = 0;

    while(timeout++ < 200)
    {
        ret = ac->Read(buff, frameSize, false);
        if (ret > 0)
        {
            printf("----->> Read: %d -- %2X %2X %2X %2X \n",
                ret,
                buff[0],
                buff[1],
                buff[2],
                buff[3]);
            
            if (fd > 0)
                write(fd, buff, ret);
        }
        else
            usleep(1000);
    }

    printf("----->> Stop(%d)\n", ac->Stop() ? 0 : (-1));
    printf("----->> Release(%d)\n", ac->Release() ? 0 : (-1));

    if (fd > 0)
        close(fd);
    delete ac;

    return 0;
}
